#include <stdio.h>
#include <stdarg.h>
#include <Windows.h>

#include "helper.h"

CHAR dbgSym[] = {
	'*',	// DEBUG_INFO.
	'+',	// DEBUG_SUCCESS.
	'!',	// DEBUG_WARNING.
	'-'		// DEBUG_ERROR.
};

WORD dbgColour[] = {
	CONSOLE_WHITE,	// DEBUG_INFO.
	CONSOLE_GREEN,	// DEBUG_SUCCESS.
	CONSOLE_YELLOW,	// DEBUG_WARNING.
	CONSOLE_RED		// DEBUG_ERROR.
};

void PrintColour(const WORD wColour, const LPSTR fmt, ...) {
	// Save the state of the console.
	CONSOLE_SCREEN_BUFFER_INFO info;
	GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info);
	// Change console colour.
	SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), wColour);

	// Print variadic arguments.
	va_list ap;
	va_start(ap, fmt);

	vprintf(fmt, ap);

	va_end(ap);

	// Restore original state of the console.
	SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), info.wAttributes);
}

void PrintDebug(const DEBUG_LEVEL l, const LPSTR fmt, ...) {
	// Print variadic arguments.
	va_list ap;
	va_start(ap, fmt);

	printf("[");
	PrintColour(dbgColour[l], "%c", dbgSym[l]);
	printf("] ");
	vprintf(fmt, ap);

	va_end(ap);
}

BOOL PromptYesNo(void) {
	while (TRUE) {
		switch (getchar()) {
			case 'Y':
			case 'y':
			case '\n':
				return TRUE;
			case 'N':
			case 'n':
				return FALSE;
			default:
				getchar();	// Absorb new line.
				PRINT_ERROR("Unrecognised input. Please try again: ");
				break;
		}
	}

	return FALSE;
}

LPVOID MyHeapAlloc(SIZE_T nSize) {
	return HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, nSize);
}

BOOL MyHeapFree(LPVOID lpMem) {
	BOOL bRet = HeapFree(GetProcessHeap(), 0, lpMem);

	// No dangling pointers!
	lpMem = NULL;

	return bRet;
}